package com.example.mealplanner.login;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.mealplanner.MainUIActivity;
import com.example.mealplanner.R;
import com.example.mealplanner.RegisterNewUser;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
public class LoginActivity extends Activity {

	public static final String PREFS_NAME = "MealPlannerCredentials";
	private static final String PREF_PHONE = "phone";
	private static final String PREF_PASSWORD = "password";
	private static final String PREF_CHECKED = "checkbox";
	private static final String PREF_USERNAME = "username";
	
	private UserLoginTask mAuthTask = null;

	// Variables
	private String mPhone;
	private String mPassword;
	private String userName;

	// UI references.
	private EditText mPhoneView;
	private EditText mPasswordView;
	private View mLoginFormView;
	private View mLoginStatusView;
	private TextView mLoginStatusMessageView;
	private CheckBox rememberCheckbox;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_login);

		// Set up the login form.
		mPhoneView = (EditText) findViewById(R.id.phone);
		mPasswordView = (EditText) findViewById(R.id.password);
		mLoginFormView = findViewById(R.id.login_form);
		mLoginStatusView = findViewById(R.id.login_status);
		mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);
		rememberCheckbox = (CheckBox) findViewById(R.id.rememberCheckBox);
		
		SharedPreferences pref = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);   
		String defaultPhone = pref.getString(PREF_PHONE, null);
		String defaultPassword = pref.getString(PREF_PASSWORD, null);
		
		if( (defaultPhone != null) && (defaultPassword != null) ){
			mPhoneView.setText(defaultPhone);
			mPasswordView.setText(defaultPassword);
			rememberCheckbox.setChecked(true);
		}
		
		
		findViewById(R.id.sign_in_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						attemptLogin();
						//loginSuccess();
					}
				});
		
		findViewById(R.id.reg_new_user_button).setOnClickListener(
				new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						createNewAccount();
					}
				});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}

	/**
	 * Attempts to sign in or register the account specified by the login form.
	 * If there are form errors (invalid email, missing fields, etc.), the
	 * errors are presented and no actual login attempt is made.
	 */
	public void attemptLogin() {
		if (mAuthTask != null) {
			return;
		}

		// Reset errors.
		mPhoneView.setError(null);
		mPasswordView.setError(null);

		// Store values at the time of the login attempt.
		mPhone = mPhoneView.getText().toString();
		mPassword = mPasswordView.getText().toString();
		
		if(rememberCheckbox.isChecked()){
			//save user credentials
			getSharedPreferences(PREFS_NAME,MODE_PRIVATE)
	        .edit()
	        .putString(PREF_PHONE, mPhone)
	        .putString(PREF_PASSWORD, mPassword)
	        .putBoolean(PREF_CHECKED, true)
	        .commit();
		}
		else{
			//clear user credentials
			getSharedPreferences(PREFS_NAME,MODE_PRIVATE)
	        .edit()
	        .putString(PREF_PHONE, null)
	        .putString(PREF_PASSWORD, null)
	        .putBoolean(PREF_CHECKED, false)
	        .commit();
		}
			
		boolean cancel = false;
		View focusView = null;

		// Check for a valid password.
		if(TextUtils.isEmpty(mPhone)){
			mPhoneView.setError(getString(R.string.error_field_required));
			focusView = mPhoneView;
			cancel = true;
		}
		if (TextUtils.isEmpty(mPassword)) {
			mPasswordView.setError(getString(R.string.error_field_required));
			focusView = mPasswordView;
			cancel = true;
		} /*else if (mPassword.length() < 4) {
			mPasswordView.setError(getString(R.string.error_invalid_password));
			focusView = mPasswordView;
			cancel = true;
		}*/

		if (cancel) {
			// There was an error; don't attempt login and focus the first
			// form field with an error.
			focusView.requestFocus();
		} else {
			// Show a progress spinner, and kick off a background task to
			// perform the user login attempt.
			Toast.makeText(getBaseContext(),"Please wait, connecting to server.",Toast.LENGTH_SHORT).show();
			mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
			showProgress(true);
			mAuthTask = new UserLoginTask();
			mAuthTask.execute(mPhone,mPassword);
			
		}
	}

	/**
	 * Shows the progress UI and hides the login form.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	private void showProgress(final boolean show) {
		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
		// for very easy animations. If available, use these APIs to fade-in
		// the progress spinner.
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			int shortAnimTime = getResources().getInteger(
					android.R.integer.config_shortAnimTime);

			mLoginStatusView.setVisibility(View.VISIBLE);
			mLoginStatusView.animate().setDuration(shortAnimTime)
					.alpha(show ? 1 : 0)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mLoginStatusView.setVisibility(show ? View.VISIBLE
									: View.GONE);
						}
					});

			mLoginFormView.setVisibility(View.VISIBLE);
			mLoginFormView.animate().setDuration(shortAnimTime)
					.alpha(show ? 0 : 1)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mLoginFormView.setVisibility(show ? View.GONE
									: View.VISIBLE);
						}
					});
		} else {
			// The ViewPropertyAnimator APIs are not available, so simply show
			// and hide the relevant UI components.
			mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
			mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
		}
	}
	
	public void createNewAccount(){
		Intent intent = new Intent(this, RegisterNewUser.class);
		startActivity(intent);
	}
	
	public void loginSuccess(){
		Intent intent = new Intent(this, MainUIActivity.class);
		startActivity(intent);
	}
	
	public void loginFailed(){
		Intent intent = new Intent(this, LoginActivity.class);
		startActivity(intent);
	}
	/**
	 * Represents an asynchronous login/registration task used to authenticate
	 * the user.
	 */
	public class UserLoginTask extends AsyncTask<String, Void, Boolean> {

		Boolean success = true;
		int result; // The result code response from server
		String message; // The message shown for the result;
		JSONObject responseMessage;
		
	    @Override
	    protected void onPostExecute(final Boolean success) {
	    	Toast.makeText(getApplicationContext(), message , Toast.LENGTH_SHORT).show();
	        if (success == true) {
	            //Do whatever your app does after login
				//Toast.makeText(getApplicationContext(), "Authentation success" , Toast.LENGTH_SHORT).show();
				loginSuccess();
	        } else {
	            //Let user know login has failed
	        	//Toast.makeText(getApplicationContext(), "Login failed", Toast.LENGTH_SHORT).show();
	        	loginFailed();
	        }
	    }

	    @Override
	    protected Boolean doInBackground(String... login) {
	    
	        
	    	HttpClient httpclient = new DefaultHttpClient();
	    	//String targetUrl = "http://www.w3schools.com/jquery/demo_test_post.asp";
	        //HttpPost httppost = new HttpPost(targetUrl);
	        String str = null;
	        String username = login[0];
	        String password = login[1];
	        String url = "http://121.199.42.184:8081/mobile/login.ashx?account="+username+"&pwd="+password;
	        Log.i("HTTPGET", url);
	        /*
	        Map map = new HashMap();
	        //map.put("account", username);
	        //map.put("pwd",password);
	        map.put("name", "Donald Duck");
	        map.put("city", "Hong Kong");
	        JSONObject jsonObject = new JSONObject(map);
	        System.out.println(jsonObject.toString());

	        
	        try {
	        	//httppost.addHeader("content-type", "application/x-www-form-urlencoded");
	            httppost.setEntity(new StringEntity(jsonObject.toString()));
	            //System.out.println(jsonObject.toString());
	        } catch (UnsupportedEncodingException e1) {
	            //e1.printStackTrace();
	        	System.out.println("HTTP POST FAILED");
	            return false;
	        }
*/
	        try {
	        	ResponseHandler<String> responseHandler = new BasicResponseHandler(); 
		        HttpGet httpGet = new HttpGet(url);
	            str = httpclient.execute(httpGet, responseHandler);
	            //Log.i("RESULT", str);
	            //str = EntityUtils.toString(response.getEntity());
	            //String content = response.getEntity().getContent().toString();
	            //if(response.getStatusLine().getStatusCode() == 200)
	       
	        }catch (Exception e) {
	            e.printStackTrace();
	        	Log.i("ERROR", "http get failed");
	        	success = false;
	        }

            //Whatever parsing you need to do on the response

	        if(str != null){
		        try {
					responseMessage = new JSONObject(str);
					result = responseMessage.getInt("Result");
					message = responseMessage.getString("Message");
		        	
					if(result==1){
			        	JSONObject data;
						data = responseMessage.getJSONObject("Data");
						userName = data.getString("UserName");
						getSharedPreferences(PREFS_NAME,MODE_PRIVATE)
				        .edit()
				        .putString(PREF_USERNAME, userName)
				        .commit();
		        	}
		        	else{
		        		success = false;
		        	}
					
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	        }
	        else{
	        	message = "Cannot connect to server";
	        }
			
	        return success;

	    }
	}
}
